#include "Dofs.h"
#include "Mesh.h"
#include "Point.h"
#include "TemplateElement.h"
#include <Eigen/Sparse>
#include <Eigen/IterativeLinearSolvers>
#include <Eigen/Dense>

/**
 * @brief 整合有限元的流程
 */
class FEM
{
public:
    /**
     * @brief 默认构造函数
     */
    FEM() = default;
    /**
     * @brief 默认析构函数
     */
    ~FEM() = default;
    void run();
private:
    /**
     * @brief 生成网格
     */
    void make_grid();
    /**
     * @brief 分配自由度，设置矩阵和向量的size
     */
    void setup_system();
    /**
     * @brief 组装刚度矩阵和右端项，处理边界条件
     */
    void assemble_system();
    /**
     * @brief 求解，共轭梯度法
     */
    void solve();
    /**
     * @brief 输出结果
     */
    void output_results() const;

    Quadrilateral_1_Element _element;/**< 模板单元类型*/
    Rectangle2D _domain;/**< 问题的定义域*/
    Mesh<2U> _mesh;/**< 划分的网格*/

    Eigen::SparseMatrix<double> system_matrix;/**< 刚度矩阵 */

    Eigen::VectorXd solution;/**< 结果 */
    Eigen::VectorXd system_rhs;/**< 右端项*/
};

double RightHandSide(Dofs<2U>& dofs) {
    //   double return_value = 0.0;
//   for (unsigned int i = 0; i < dim; ++i)
//       return_value += 4.0 * std::pow(p(i), 4.0);
//   return return_value;
    return 1;
}



double BoundaryFunction(Dofs<2U>& dofs)
{
    //return dofs[0]*dofs[0] + dofs[1]*dofs[1];
    return 0;
}


/**
 * This function does the first part, creating the mesh. We create the mesh
 * which is the square [−1,1]×[−1,1].
 */
void FEM::make_grid()
{
    vector<Point<2>> p = {{-1.0,-1.0},{1.0,-1.0},{1.0,1.0},{-1.0,1.0}};
	_domain.setVertexList(p);
    Mesh<2> mesh(_domain,{2,2});//n等分
    _mesh = mesh;
}



/**
 * Next we enumerate all the degrees of freedom and set up matrix and vector objects to hold the system data.
 *
 */
void FEM::setup_system()
{
    /*Enumerating is done by using DistributeDofs(),2-order element*/
    _mesh.distributeDofs(1);
    std::cout << "Number of degrees of freedom: " << _mesh.getTotalNumDofs() << std::endl;

    /**
     * set the sizes of system_matrix, right hand side vector ans the solution vector;
     */
    system_matrix = Eigen::SparseMatrix<double>(int(_mesh.getTotalNumDofs()),int(_mesh.getTotalNumDofs()));
    system_matrix.setZero();
    system_rhs = Eigen::VectorXd::Zero(int(_mesh.getTotalNumDofs()));
    solution = Eigen::VectorXd::Zero(int(_mesh.getTotalNumDofs()));
    std::cout << "setup system is done" << std::endl;
}


/**
 * The next step is to compute the entries of the matrix
 * and right hand side that form the linear system from which we compute the solution.
 */
void FEM::assemble_system()
{
    /**
     * Get the right_hand_side function and boundary function
     */
    std::function<double(Dofs<2U>&)> right_hand_side = RightHandSide;
    std::function<double(Dofs<2U>&)> boundary_function = BoundaryFunction;



    /**
     * for each Grid, we construct a cell_matirx and cell_rhs.
     */
    const unsigned int dofs_per_cell = _element.n_Dofs();
    Eigen::MatrixXd cell_matrix(dofs_per_cell,dofs_per_cell);
    Eigen::VectorXd cell_rhs(dofs_per_cell);
    Quadrilateral_Element_GaussianInfo gauss;//加入gauss点
    gauss.LoadGaussianInfo(1);
    std::cout << "gauss points is added " << std::endl;

    /*assemble the global matrix and vector cell-by-cell.*/
    for (auto &cell : _mesh.getGridVector())
    {
    	// bind the TemplateElement with current cell.
	_element.reinit(cell);

	cell_matrix = Eigen::MatrixXd::Zero(dofs_per_cell,dofs_per_cell);
	cell_rhs    = Eigen::VectorXd::Zero(dofs_per_cell);
	for (int q_index = 0; q_index < _element.n_GaussPnt();++q_index)
        {
	    //std::cout << "GaussPnt number is: " << _element.n_GaussPnt() << std::endl;
	    Point<2> pnt = gauss.GaussianPointInfo(q_index);
	    //std::cout << "point: " << pnt << std::endl;
	    //自下面开始注意标号...一致性
	    for (int i = 0; i < dofs_per_cell; ++i)
	    {
		for (int j = 0; j < dofs_per_cell; ++j)
		{
		    double InnerProduct = 0;
		    for(int k = 0;k < _element.gradient(pnt[0],pnt[1],i+1).size();k++)
		    {

			InnerProduct += _element.gradient(pnt[0],pnt[1],i+1)[k] *
			    _element.gradient(pnt[0],pnt[1],j+1)[k];
		    }
		    cell_matrix(i, j) +=(InnerProduct *
					 _element.det_Jacobi(pnt[0], pnt[1]) *
					 _element.GaussionWeight(q_index));
		}
	    }
	    double xi = pnt[0],eta = pnt[1];
	    double x = _element.Global_x(xi, eta);
	    double y = _element.Global_y(xi, eta);
	    for (int i = 0; i < dofs_per_cell; ++i)
	    {
		//vector<double> p({x,y});
		Point<2> p({x,y});

		Dofs<2> globalDof(p);
		cell_rhs(i) += ( _element.phi(xi, eta, i + 1) *
				 right_hand_side(globalDof) *
				 _element.det_Jacobi(xi, eta) *
				 _element.GaussionWeight(q_index));
	    }

	}

	for (int i = 0; i < dofs_per_cell; ++i)
	{
	    for (int j = 0; j < dofs_per_cell; ++j)
	    {
		int row = _element.GetGlobalIndex(i+1);
		int column = _element.GetGlobalIndex(j+1);
		system_matrix.coeffRef(row, column)+=cell_matrix(i, j);
	    }
	}
	for (int i = 0; i < dofs_per_cell; ++i)
	    system_rhs[_element.GetGlobalIndex(i+1)] += cell_rhs(i);
    }
    system_matrix.makeCompressed();

    std::vector<Dofs<2>> boundary_dofs = _mesh.getBoundaryDofs();
    std::map<int, double> boundary_values;

    boundary_values = _mesh.interpolateBoundaryValues(boundary_function,boundary_dofs);

    _mesh.applyBoundaryValues(boundary_values,system_matrix,system_rhs);
	cout << system_rhs << endl;

    std::cout << "assemble system is done" << std::endl;
}



void FEM::solve()
{
    /**
     *  stop if the norm of the residual is below τ=1e−6*||b|| where b is the right hand side vector
     */
    Eigen::ConjugateGradient<Eigen::SparseMatrix<double>,Eigen::Lower|Eigen::Upper> cg;
    cg.compute(system_matrix);
    cg.setTolerance(1e-16);
    solution = cg.solve(system_rhs);
    std::cout << "#iterations:     " << cg.iterations() << std::endl;
    std::cout << "estimated error: " << cg.error()      << std::endl;
	cout << solution << endl;

}




void FEM::output_results() const
{

}



void FEM::run()
{
	cout <<"make grid:"<<endl;
	make_grid();
	cout <<"setup system:"<<endl;
	setup_system();
	cout <<"assemble_system"<<endl;
	assemble_system();
	cout <<"solve:" <<endl;
	solve();
    output_results();
}



int main()
{
    FEM laplace_problem;
    laplace_problem.run();
    return 0;
}
